<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { isOpens } from "@/utils/directive.js";
import {
  appReceiveQuery,
  appSelectorAll,
  purchaseCount,
} from "@/services/send";

// import { purchaseQuery } from "@/services/delivery";

// import tabbarView from "../components/tabbar.vue";
const topHeight = ref(uni.getStorageSync("topHight") || 0);
const scrollTop = ref(0);
const code = ref("");
const storeCenter = ref([]);
const showSelect = ref("");

onLoad((option) => {
  code.value = option.code ? option.code : "";
  form.value.keyword = option.code ? option.code : "";
  getAppProductQuery(1);
  getAppSelectorAll();
});
onShow(() => {
  if (uni.getStorageSync("selectShopType")) {
    showSelect.value = uni.getStorageSync("selectShopType");

    // getChartCategory();
    // getChartProduct();
  }
  if (isOpens(["manager:purchase:query"]) || isOpens(["shop:purchase:query"])) {
    getPurchaseCount();
  }
});

const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getAppProductQuery(1);
};
const getAppSelectorAll = async () => {
  try {
    let res = await appSelectorAll({ pageIndex: 1, pageSize: 9999 });
    if (res.code == 200) {
      storeCenter.value = res.data.datas;
    } else {
    }

    console.log(res);
  } catch (e) {}
};
const purchaseCountObj = ref({});
const getPurchaseCount = async () => {
  let res = await purchaseCount();

  purchaseCountObj.value = res.data.statusCounts;
};

onReachBottom(() => {
  getAppProductQuery();
});

//获取商品
const form = ref({
  pageIndex: 1,
  pageSize: 20,
  createStartTime: "",
  createEndTime: "",
  scId: "",
  keyword: "",
});

const productData = ref([]);

const loading = ref("");
const getAppProductQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "Loading";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await appReceiveQuery(form.value);
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.datas);
      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//编辑商品
const goEdt = (item) => {
  uni.navigateTo({ url: "/pages/sends/det/index?id=" + item.id });
};
const ishowcamera = ref(false);
const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=goods" });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码

  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.keyword = res.result;
                  getAppProductQuery(1);
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keyword = res.result;
      getAppProductQuery(1);
    },
  });
  // #endif
};
const searchFun = () => {
  console.log("搜索");
  uni.navigateTo({
    url: "/pages/goods/goods_search/index",
  });
};
const goadd = () => {
  uni.navigateTo({
    url: "/pages/sends/listsends/index",
  });
};
const keyword = ref("");
const searchlistfun = () => {
  form.value.keyword = keyword.value;
  getAppProductQuery(1);
};

const upper = (e) => {
  console.log(e);
};
const lower = (e) => {
  console.log(e);
};
const scroll = (e) => {
  console.log(e);
};
const sandfun = (item) => {
  uni.navigateTo({
    url: "/pages/delivery/send/index?id=" + item.id,
  });
};

//筛选弹框
const showShop = ref(false);
const selectType = ref(0);

const selectCk = () => {
  if (selectType.value != 1 && showShop.value == true) {
  } else {
    showShop.value = !showShop.value;
  }
  if (!showShop.value) {
    selectType.value = 0;
  } else {
    selectType.value = 1;
  }
};
const selectTM = () => {
  // showShop.value = true;
  // selectType.value = 2;

  if (selectType.value != 2 && showShop.value == true) {
  } else {
    showShop.value = !showShop.value;
  }
  if (!showShop.value) {
    selectType.value = 0;
  } else {
    selectType.value = 2;
  }
  // selectDateIndex.value = 0;
};

//时间选择
const showtime = ref(false);
const showEndTime = ref(false);
const datetimePickerRef = ref(null);
const timevalue = ref(Time(Date.now()));
const timevalueTwo = ref(Time(Date.now()));
const minTime = ref("");
const selectDateIndex = ref(0);

const selectDate = (index) => {
  selectDateIndex.value = index;
  if (selectDateIndex.value == 1) {
    showtime.value = true;
  }
  if (selectDateIndex.value == 2) {
    showEndTime.value = true;
  }
  // showShop.value = false;
};

const confirmDate = (E) => {
  minTime.value = Time(E.value);
  timevalue.value = Time(E.value);
  timevalueTwo.value = Time(Date.now(timevalue.value));

  showtime.value = false;
  showEndTime.value = true;
};
const confirmDateTwo = (E) => {
  timevalueTwo.value = Time(E.value);
  showEndTime.value = false;
  selectDateIndex.value == 2;
  showShop.value = true;
};
function Time(e) {
  const date = new Date(e);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const selectShop = (item, index) => {
  form.value.scId = item.id;
};

const cancel = () => {
  // let num = 0;
  showShop.value = false;
  selectDateIndex.value = 0;
  selectType.value = 0;
  form.value.scId = "";
  getAppProductQuery(1);

  // if (selectDataList.value.length > 0) {
  //   introData.value.forEach((item2) => {
  //     item2.select = false;
  //   });

  //   selectDataList.value.forEach((item) => {
  //     introData.value.forEach((item2) => {
  //       if (item2.shopId == item.shopId) {
  //         item2.select = true;
  //         num++;
  //       }
  //     });
  //   });
  //   selectShopNum.value = num;
  // }
};
const qrFun = () => {
  if (selectDateIndex.value > 0) {
    form.value.createStartTime = timevalue.value + " 00:00:00";
    form.value.createEndTime = timevalueTwo.value + " 23:59:59";
  } else {
    form.value.createStartTime = "";
    form.value.createEndTime = "";
  }
  showShop.value = false;

  getAppProductQuery(1);
};

//无网状态
const connected = () => {
  getAppProductQuery(1);
  getAppSelectorAll();
};
</script>

<template>
  <topNav
    title="收货单"
    @search="searchFun"
    @scan="scanFun"
    rType="save"
    :clickable="false"
  ></topNav>
  <view class="pay-top" :style="'top: calc( 88rpx + ' + topHeight + 'px);'">
    <view class="pay-search">
      <view class="pay-search-left">
        <up-search
          style="height: 60rpx"
          placeholder="单据编号/操作人"
          v-model="keyword"
          @search="searchlistfun"
          :showAction="false"
          shape="square"
        ></up-search>
      </view>
      <view
        class="pay-search-right"
        @click="selectCk"
        v-if="showSelect == 'admin'"
      >
        <text :class="selectType == 1 ? 'play-color' : ''">仓库</text>
        <up-icon
          class="play-right-fill"
          name="play-right-fill"
          :class="selectType == 1 ? 'play-right-fill-rad' : ''"
          :color="selectType == 1 ? '#1679fb' : '#c9cdd4'"
          size="24rpx"
        ></up-icon>
      </view>
      <view class="pay-search-right" @click="selectTM">
        <text :class="selectType == 2 ? 'play-color' : ''">时间</text>
        <up-icon
          class="play-right-fill"
          name="play-right-fill"
          :class="selectType == 2 ? 'play-right-fill-rad' : ''"
          :color="selectType == 2 ? '#1679fb' : '#c9cdd4'"
          size="24rpx"
        ></up-icon>
      </view>
    </view>
  </view>

  <view class="goods_form">
    <view
      class="scr_item"
      v-for="(item, index) in productData"
      :key="index"
      @click="goEdt(item)"
    >
      <view class="item_title" @click.stop>
        <view class="item_title_left">
          <text>{{ item.createTime }}</text>
          <!-- <image src="@/static/images/copy.png" mode="scaleToFill" /> -->
        </view>

        <!-- <text class="state">{{ item.deliverStatusName }}</text> -->
      </view>

      <view class="item_content">
        <view class="item_content-list">
          <view class="item_content-item">
            <view class="item_content-left"> 接收仓库</view>
            <text>{{ item.scName }}</text>
          </view>
          <view class="item_content-item">
            <view class="item_content-left"> 接收人</view>
            <text>{{ item.createBy }}</text>
          </view>
          <view class="item_content-item">
            <view class="item_content-left"> 金额</view>
            <text>{{ item.totalAmount }}</text>
          </view>
          <view class="item_content-item">
            <view class="item_content-left"> 数量合计</view>
            <text>{{ item.totalNum }}</text>
          </view>
          <view class="item_content-item" style="width: 100%">
            <view class="item_content-left"> 单据编号</view>
            <text>{{ item.code }}</text>
          </view>
        </view>
        <!-- <view class="item_content-right">
          <view>
            <view class="item_content-right-11"
              ><text>¥</text>{{ item.totalAmount }}
            </view>
            <view class="item_content-right-22">{{ item.totalNum }}件</view>
          </view>
        </view> -->
      </view>

      <!-- <view class="bt_foods">
        <view class="bt_fh bt_qx" @click.stop>取消</view>
        <view class="bt_fh bt_qr" @click.stop="sandfun(item)">发货</view>
      </view> -->
    </view>
  </view>
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无收货单 </view>
    </view>
  </view>
  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>

  <!-- <view style="width: 100%; height: 100rpx"></view> -->

  <!-- <view class="goods_bt">
    <view class="goods_bt_to"
      ><up-button
        @click="goadd"
        class="goods_bt_to_btn"
        icon="plus"
        iconColor="#ffffff"
      >
        <view class="bt_new">
          <text>去收货</text>
          <up-badge
            class="bt_badge"
            bgColor="#F53F3F"
            max="99"
            :value="purchaseCountObj['5'] || 0"
          ></up-badge
        ></view>
      </up-button>
    </view>
  </view> -->

  <view class="popup_data">
    <up-datetime-picker
      class="top-center"
      :hasInput="false"
      title="选择开始时间"
      @close="showtime = false"
      @confirm="confirmDate"
      @cancel="showtime = false"
      format="YYYY-MM-DD"
      :show="showtime"
      v-model="timevalue"
      :closeOnClickOverlay="true"
      mode="date"
    >
    </up-datetime-picker>

    <up-datetime-picker
      class="top-center"
      :hasInput="false"
      title="选择结束时间"
      @close="showEndTime = false"
      @confirm="confirmDateTwo"
      @cancel="showEndTime = false"
      format="YYYY-MM-DD"
      :minDate="minTime"
      :show="showEndTime"
      v-model="timevalueTwo"
      :closeOnClickOverlay="true"
      mode="date"
    >
    </up-datetime-picker>
  </view>

  <!-- 筛选 -->
  <up-popup
    :show="showShop"
    mode="top"
    @close="showShop = false"
    round="15"
    :safeAreaInsetTop="true"
  >
    <view class="popup">
      <scroll-view
        :scroll-top="0"
        scroll-y="true"
        class="scroll-Y"
        @scrolltoupper="upper"
        v-if="selectType == 1"
      >
        <view
          class="popup_item"
          v-for="(item, index) in storeCenter"
          :key="index"
          @click="selectShop(item, index)"
        >
          <view class="popup_item_left"
            ><text></text> <text>{{ item.name }}</text>
          </view>

          <view class="popup_item_right" v-if="form.scId == item.id">
            <up-icon
              name="checkbox-mark"
              color="#1679fb"
              size="42rpx"
            ></up-icon>

            <!-- <view class="popup_item_right_o"></view>
            <image src="@/static/manage/select.png" mode="scaleToFill" /> -->
          </view>
        </view>
      </scroll-view>

      <view class="select_Time" v-if="selectType == 2">
        <view class="select_Time-item">
          <view
            class="select_Time-item_left"
            :class="selectDateIndex == 1 ? 'select_Time-item_left-top' : ''"
            @click="selectDate(1)"
            >{{ timevalue }}</view
          >
          <text>至</text>
          <view
            class="select_Time-item_left"
            :class="selectDateIndex == 2 ? 'select_Time-item_left-top' : ''"
            @click="selectDate(2)"
            >{{ timevalueTwo }}</view
          >
        </view>
      </view>

      <view style="width: 100%; height: 30rpx"></view>

      <view class="popup_bt">
        <view class="popup_bt_qx" @click="cancel">取消</view>
        <view class="popup_bt_qr" @click="qrFun">确认</view>
      </view>
    </view>
  </up-popup>

  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
